class Solution:
    def minTime(self, n: int, edges: list, hasApple: list) -> int:
        def dfs(adj, node, hasApple, visited):
            visited.add(node)
            if len(adj[node]) == 0:
                return 0
            res = 0
            for n in adj[node]:
                if n in visited:
                    continue
                ans = dfs(adj, n, hasApple, visited)
                if ans > 0 or hasApple[n]:
                    res += 2
                res += ans

            return res

        adj = [[] for _ in range(n)]
        for edge in edges:
            adj[edge[0]] += [edge[1]]
            adj[edge[1]] += [edge[0]]

        return dfs(adj, 0, hasApple, set())
